<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "yyh_job".
 *
 * @property int $id
 * @property string $name 职位名
 * @property string|null $menu_powers 菜单操作权限
 * @property string|null $patient_powers 患者操作权限
 */
class Job extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'yyh_job';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['menu_powers', 'patient_powers'], 'string'],
            [['name'], 'string', 'max' => 32],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '职位名',
            'menu_powers' => '菜单操作权限',
            'patient_powers' => '患者操作权限',
        ];
    }

    public static function getOptions()
    {
        $res = [];
        $jobs = Job::find()->all();
        if (null != $jobs && count($jobs) > 0) {
            foreach ($jobs as $j) {
                $res[$j->id] = $j->name;
            }
        }

        return $res;
    }

    public function check_menu($menu_id_or_url = '')
    {
        if ($this->name == '超级管理员') {
            return true;
        }

        if (is_int($menu_id_or_url) && in_array($menu_id_or_url, explode(',', $this->menu_powers))) {
            return true;
        }

        if (is_string($menu_id_or_url)) {
            $menu = Menu::find()->where("url = '{$menu_id_or_url}'")->one();
            if (null != $menu && in_array($menu->id, explode(',', $this->menu_powers))) {
                return true;
            }
        }

        return false;
    }

    public function check_patient_power($power_id_or_instruction = '')
    {
        $patient_power = array();
        if (is_int($power_id_or_instruction)) {
            $patient_power = Patientpower::findOne($power_id_or_instruction);
        } else if (is_string($power_id_or_instruction)) {
            $patient_power = Patientpower::find()->where("var_name = '{$power_id_or_instruction}'")->one();
        }

        if ($this->name == '超级管理员') {
            return 'super';
        } else if (null != $patient_power && in_array($patient_power->id, explode(',', $this->patient_powers))) {
            if (null == $patient_power) {
                return '没有找到权限';
            } else {
                return $patient_power->operate;
            }
        } else {
            return 'failure';
        }
    }
}
